<template>
  <el-dialog
    :title="tableRelationTitle"
    :visible.sync="tableRelationDialogVisible"
    width="30%"
    :close-on-click-modal="false"
    :before-close="TableRelationDialogClose"
    @close="closeDialog"
  >
    <div>
      <el-form ref="tableRelationForm" :model="tableRelationForm" :rules="tableRelationRules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="表关系名称" prop="relationName">
              <el-input v-model="tableRelationForm.relationName" placeholder="请输入表关系名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="主表名" prop="mainTableName">
              <el-select
                v-model="tableRelationForm.mainTableName"
                placeholder="请选择主表名"
                @change="changeMainTableName"
              >
                <el-option
                  v-for="(item,index) in TableNameOptions"
                  :key="index"
                  :label="item.tableAlias"
                  :value="item.recNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="子表名" prop="childTableName">
              <el-select
                v-model="tableRelationForm.childTableName"
                placeholder="请选择子表名"
                @change="changeChildTableName"
              >
                <el-option
                  v-for="(item,index) in TableNameOptions"
                  :key="index"
                  :label="item.tableAlias"
                  :value="item.recNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="主表字段" prop="mainTableField" >
              <el-select
                v-model="tableRelationForm.mainTableField"
                placeholder="请选择主表字段"
                @change="$forceUpdate()"
              >
                <el-option
                  v-for="(item,index) in mainTableFieldOptions"
                  :key="index"
                  :label="item.fieldAlias"
                  :value="item.recNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="子表字段" prop="childTableField">
              <el-select
                v-model="tableRelationForm.childTableField"
                placeholder="请选择主表名"
                @change="$forceUpdate()"
              >
                <el-option
                  v-for="(item,index) in childTableFieldOptions"
                  :key="index"
                  :label="item.fieldAlias"
                  :value="item.recNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="18">
            <el-form-item label="表关系信息">
              <ul class="info">
                <li
                  v-for="(item,index) in info"
                  :key="index"
                  :class="item.showSelectbg ? 'bg' : ''"
                  @click="selectInfoItem(index)"
                >{{item.content}}</li>
              </ul>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div class="add-btn">
              <el-button size="mini" type="primary" @click="add">添加</el-button>
            </div>
              <div class="del-btn">
                <el-button size="mini" @click="del">删除</el-button>
              </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="TableRelationDialogClose">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  addTableRelation,
  getTableRelationFieldList,
  updateTableRelation,

} from '@/api/system/sort'

export default {
  name: 'tableRelationDialog',
  props:['tableRelationForm','tableRelationDialogVisible','tableRelationTitle','TableNameOptions','queryParams','getTableRelation'],
  data() {
    return {
      info:[],
      tableRelationRules:{
        relationName:[
          {required:true,message:'请输入表关系名称',trigger:'blur'}
        ],
        mainTableName:[
          {required:true,message:'请选择主表名',trigger:'blur'}
        ],
        childTableName:[
          {required:true,message:'请选择子表名',trigger:'blur'}
        ],
        mainTableField:[
          {required:true,message:'请选择主表字段',trigger:'blur'}
        ],
        childTableField:[
          {required:true,message:'请选择子表字段',trigger:'blur'}
        ],
        info:[
          {required:true,message:'请至少添加一个关联字段',trigger:'blur'}
        ]
      },
      mainTableFieldOptions:[
        {
          recNo:'',
          fieldAlias:''
        }
      ],
      childTableFieldOptions:[
        {
          id:'001',
          name:'测试'
        }
      ],
      showSelectbg:false,
      delIndex:''
    };
  },
  methods:{
    closeDialog(){
      for (const key in this.tableRelationForm) {
        this.tableRelationForm[key] = ''
      }
      this.info = []
    },

    TableRelationDialogClose(){
      this.$emit('closeTRelationDia')
    },
    // 选择主表名
    async changeMainTableName(recNo){
      // 获取表关系表字段列表
        this.tableRelationForm.mainTableField = ''
        const res = await getTableRelationFieldList({fieldName:'',recNo})
        this.mainTableFieldOptions = res.rows
    },
    // 选择子表名
    async changeChildTableName(recNo){
      // 获取表关系表字段列表
      this.tableRelationForm.childTableField = ''
      const res = await getTableRelationFieldList({fieldName:'',recNo})
      this.childTableFieldOptions = res.rows
    },
    // 添加
    add() {
      const mainNameIndex = this.TableNameOptions.findIndex(item => item.recNo === this.tableRelationForm.mainTableName)
      const childNameIndex = this.TableNameOptions.findIndex(item => item.recNo === this.tableRelationForm.childTableName)
      const mainName = mainNameIndex === -1 ? this.tableRelationForm.mainTableName : this.TableNameOptions[mainNameIndex].tableAlias
      const childName = childNameIndex === -1 ? this.tableRelationForm.childTableName : this.TableNameOptions[childNameIndex].tableAlias
      if(mainName === childName){
        return this.$message.error('无法对同一张表添加关系，请重新选择')
      }
      if(this.tableRelationForm.mainTableField.length === 0 ||this.tableRelationForm.childTableField.length === 0){
        return this.$message.error('请选择主表字段和子表字段')
      }
       const index1 = this.mainTableFieldOptions.findIndex(item => item.recNo === this.tableRelationForm.mainTableField)
       const index2 = this.childTableFieldOptions.findIndex(item => item.recNo === this.tableRelationForm.childTableField)
      let mainFieldAlias = index1 === -1 ? this.tableRelationForm.mainTableField : this.mainTableFieldOptions[index1].fieldAlias
      let childFieldAlias = index2 === -1 ? this.tableRelationForm.childTableField : this.childTableFieldOptions[index2].fieldAlias
      const content = mainFieldAlias + ' ' + '|' + ' ' + childFieldAlias
      const exIndex = this.info.findIndex(item => (item.content === content))
        if(exIndex !== -1){
          return this.$message.error('此字段关联已存在，请不要重复设置')
        }
        this.info.push({
          content,
          showSelectbg:false
        })
    },
    // 选择删除项
    selectInfoItem(index){
      this.delIndex = index
      this.info.forEach(item => {
        item.showSelectbg = false
      })
      this.info[index].showSelectbg = true
    },
    // 删除
    del(){
      if(this.delIndex === ''){
        return this.$message.info('请选择删除项')
      }
      this.info.splice(this.delIndex,1)
      this.delIndex = ''
    },
    //  获取表关系表字段列表

    // 保存
     save(){
       // console.log(232,this.tableRelationForm.update)
      this.$refs.tableRelationForm.validate(async (valid) => {
        if (!valid) {
          return
        }
          this.$confirm('确认提交吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const arTableRelation ={
              sortNo:this.queryParams.sortPrantNo,
              relationName:this.tableRelationForm.relationName,
              parentNo:this.tableRelationForm.mainTableName,
              childNo:this.tableRelationForm.childTableName,
              arTableFiledRelation:{
                parentFiled:this.tableRelationForm.mainTableField,
                childFiled:this.tableRelationForm.childTableField,
              }
            }
            if(this.tableRelationForm.update === '新增'){
              this.submitAdd(arTableRelation)
            }else {
              this.update(arTableRelation)
            }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消提交'
          });
        });
      });
      },
      async submitAdd(arTableRelation){
        const res = await addTableRelation(arTableRelation)
        if(res.code === 200){
          this.$message.success(res.msg)
          this.TableRelationDialogClose()
          this.getTableRelation()
        }
      },
      async update(arTableRelation){
        const res = await updateTableRelation(arTableRelation)
        if(res.code === 200){
          this.$message.success(res.msg)
          this.TableRelationDialogClose()
          this.getTableRelation()
        }
      }
  },
}
</script>

<style scoped>
ul{
  padding: 0;
  margin: 0;
  list-style: none;
}
li{
  cursor: pointer;
  margin: 3px 0;
}
.add-btn,.del-btn{
  padding: 0 0 5px 30px;
}
.info{
  width: 300px;
  height: 150px;
  overflow: auto;
  border: 1px solid #dcdfe6;
}
.bg{
  background-color: #f5f7fa;
}
</style>
